<template>
  <div>
    <el-card>
      <el-tree
        ref="tree"
        :props="props"
        :data="menuData"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedKeys"
        :default-expand-all="true"
      >
      </el-tree>
      <div style="margin-top: 20px; text-align: center">
        <el-button type="primary" size="small" @click="updateMenu"
          >保存</el-button
        >
        <el-button size="small" @click="clear">清空</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getRoleMenuById, getAllMenus, updateAllocMenu } from "@/request/api";
export default {
  data() {
    return {
      menuData: [],
      props: {
        label: "title",
      },
      checkedKeys: [],
      roleId: '',
    };
  },
  methods: {
    updateMenu() {
      this.$confirm(`此操作将删除当前用户, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let checkKeys = this.$refs.tree.getCheckedNodes();
          let keySet = new Set();
          for (let i = 0; i < checkKeys.length; i++) {
            if (checkKeys[i].parentId != 0) {
              keySet.add(checkKeys[i].parentId);
            }
            keySet.add(checkKeys[i].id);
          }

          let menuIds = Array.from(keySet).join(",");
          updateAllocMenu({
              menuIds,
              roleId: this.roleId
          }).then((res) => {
              if (res.code === 200) {
                  this.$message.success(res.message);
                  this.$router.replace('/ums/role')
              }
          });
        })
        .catch(() => {});
    },
    clear() {
      this.$refs.tree.setCheckedKeys([]);
    },
  },
  async created() {
    this.roleId = this.$route.query.id;
    let res = await getAllMenus();
    if (res.code === 200) {
      this.menuData = res.data;
    }
    let res1 = await getRoleMenuById(this.roleId);
    if (res1.code === 200) {
      this.checkedKeys = res1.data.reduce((prev, current) => {
        if (current.parentId != 0) {
          prev.push(current.id);
        }
        return prev;
      }, []);
    }
  },
};
</script>

<style>
</style>